package Network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class TcpEchoService {
    //创建⼀个服务端流套接字Socket，并绑定到指定端⼝创建⼀个服务端流套接字Socket，
    // 并绑定到指定端⼝
    private ServerSocket serverSocket=null;
    public TcpEchoService(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService pool = Executors.newCachedThreadPool();
        while(true) {
            //通过accept 接听连接
            Socket clientSocket = serverSocket.accept();
            //建立连接
//        new Thread(()->{
//            processConnection(clientSocket);
//
//        }).start();
//        }
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }
    //通过这个方法来处理一次连接. 连接建立的过程中就会涉及到多次的请求响应交互.
    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s,%d] 客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()){
            //// 循环的读取客户端的请求并返回响应.
            while(true) {
                Scanner scan=new Scanner(inputStream);
                if(!scan.hasNext()){
                    //// 读取完毕. 客户端断开连接, 就会产生读取完毕.
                    System.out.printf("[%s,%d] 客户端下线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //读取客户端请求
                String request=scan.next();
                //处理客户端请求 并响应
                String response = process(request);
                //将响应返回给客户端
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();//通过flush 刷新确保数据被发送出去
                System.out.printf("[%s,%d] req:%s, resp:%s\n",clientSocket.getInetAddress(),clientSocket.getPort()
                                                            ,request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoService tcpEchoService = new TcpEchoService(9090);
        tcpEchoService.start();
    }
}

class TcpEchoServer1{
    //创建ServerSocket对象
    private ServerSocket serverSocket=null;
    //提供客户端端口号
    public TcpEchoServer1(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务端启动");
        ExecutorService pool = Executors.newCachedThreadPool();
        while(true){
            //1.通过accpet方法 接听连接
            Socket clientSocket = serverSocket.accept();
            //2.通过实现processConnection方法 建立连接
//            processConnection(clientSocket);
            pool.submit(new Runnable(){//通过线程池,创建多条线程
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }
    //TCP是以字节流的方式发送请求的,要用InputStream来读取发送的请求,
                        //    用OutputStream来 返回响应
    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s,%d] 客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()) {
            //循环读取客户端的请求,并返回响应
           while(true){
               //1.读取请求
               Scanner scan=new Scanner(inputStream);
               if(!scan.hasNext()){
                   //读取完毕,客户端断开连接,产生 读取完毕
                   System.out.printf("[%s,%d] 客户端下线\n",clientSocket.getInetAddress(),clientSocket.getPort());
                   break;
               }
               //2,请求并解析 注意:next读取到空白字符才结束
               String request=scan.next();
               //3.根据请求,计算响应
               String response=process(request);
               //4.把响应返回给客户端
               //给outputStream套上一层,可以获取 \n 更方便操作
               PrintWriter printWriter=new PrintWriter(outputStream);
               printWriter.println(response);
               printWriter.flush();//手动刷新缓冲区
               System.out.printf("[%s,%d] req:%s, resp:%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),
                                    request,response);

           }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String process(String request) {
        //这里还是什么都不做,就返回请求
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer1 tcpEchoServer1 = new TcpEchoServer1(9090);
        tcpEchoServer1.start();
    }
}